<?php

namespace support\Service;

use support\Backend\BackendService;
use support\Container;
use support\Model\MenuModel;
use support\Model\RoleMenuModel;
use support\Model\RoleModel;

class RoleService extends BackendService
{

    private  $menuModel;
    private $roleMenuModel;

    public function __construct()
    {
        $this->model = Container::get(RoleModel::class);
        $this->menuModel = Container::get(MenuModel::class);
        $this->roleMenuModel=Container::get(RoleMenuModel::class);
    }

    /**
     * 获取角色列表
     */
    public function getRoleList()
    {
        $list = $this->model->where([
            ['status', '=', 1],
            ['mark', '=', 1],
        ])->orderBy("sort")->get();
        return $list ? $list->toArray() : [];
    }


    /**
     * 获取权限列表
     * @return array
     * @since 2020/11/20
     */
    public  function getPermissionList($role_id): array
    {
        // 获取全部菜单
        $menuList = $this->menuModel->select(['id', 'title', 'sort', 'pid'])->where([
            ['status', '=', 1],
            ['mark', '=', 1],
        ])->orderBy("sort")->get()->toArray();
        if (!$menuList) return [];
        //判断是否超级角色
        if ($role_id != env('SUPER_ADMIN')) {
            $roleMenuList = $this->roleMenuModel
                ->select(["menu_id"])
                ->where("role_id", '=', $role_id)
                ->get()->toArray();
            $menuIdList = array_key_value($roleMenuList ?: [], "menu_id");
        } else {
            $menuIdList = array_key_value($menuList, "id");
        }
        foreach ($menuList as &$val) {
            $val['checked'] = $val['open'] = false;
            if (in_array($val['id'], $menuIdList)) {
                $val['checked'] = true;
                $val['open'] = true;
            }
        }
        return $menuList;
    }


}
